package club.kingyin.easycache.component.annotation.handler;

import club.kingyin.easycache.key.AbstractEasyCacheKey;
import club.kingyin.easycache.component.InjectPostProcess;
import club.kingyin.easycache.component.Pram;
import club.kingyin.easycache.component.annotation.Param;
import club.kingyin.easycache.utils.AnnotationUtils;
import club.kingyin.easycache.utils.InstanceUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;

@Slf4j
public class AnnotationParamFiledPostProcess implements InjectPostProcess {
    @Override
    public void postProcessBeforeInject(Annotation[] annotation, AbstractEasyCacheKey key, Pram pram) {
        Param param = null;
        for (Annotation params : annotation) {
            if (params.annotationType().equals(Param.class)) {
                param = (Param) params;
            }
        }
        if (param == null) {
            return;
        }
        if (!AnnotationUtils.PRAM_NULL.equals(param.name())) {
            pram.setPramName(param.name());
        }
        // value优先级大于ref
        if (!AnnotationUtils.PRAM_NULL.equals(param.value())) {
            // 基本类型强制转换
            Object value = InstanceUtils.switchByType(param.value(), param.type());
            log.debug("模块：[{}] 方法：[{}] 参数修改(类型转换) {} -> {}", key.getModule(), key.getMethodName(), pram.getPram(),value);

            pram.setPram(value);
        } else if(!AnnotationUtils.PRAM_NULL.equals(param.ref())) {
            Object ref = key.getPram(param.ref());
            log.debug("模块：[{}] 方法：[{}] 参数修改(引用覆盖) {} -> {}", key.getModule(), key.getMethodName(), pram.getPram(),ref);
            pram.setPram(ref);
        }
    }

    @Override
    public boolean postProcessPreInject(boolean pre, Annotation[] annotation, AbstractEasyCacheKey key,Pram pram) {
        return pre;
    }

    @Override
    public void postProcessAfterInject(boolean isInject, Annotation[] annotation, AbstractEasyCacheKey key,String paramName, Object param) {
        if (isInject) {

        }
    }
}
